<template>
  <div class="container">
    <normal-title
      title='结算'
      :back="true"
    ></normal-title>
    <div
      class="card"
      v-for="(item, index) in orderInfo.items"
      :key="index"
    >
      <img
        class="thumb"
        :src="item.image"
        mode="aspectFit"
      >
      <div class="info">
        <p class="text">{{item.product_name}}</p>
        <div class="spec">规格: {{item.item_no}}</div>
        <div class="row">
          <p class="price"><span class="price-icon">￥</span>{{item.real_price}}</p>
          <div class="count">X {{item.num}}</div>
        </div>
      </div>
    </div>
    <div class="session">
      <div class="row">
        <div class="item-name">优惠券码</div>
        <input
          class="discount"
          type="text"
          v-model="discountCode"
          @input="checkCode"
        >
        <div
          class="tips"
          v-if='discount!=null'
        >{{discount.message}}</div>
      </div>
      <div class="split"></div>
      <div class="row">
        <div class="item-name">配送方式</div>
        <div class="fake"></div>
        <div @click="choiceWay(0)">
          <img
            class="choice-icon"
            :src="getWay===0?'../../images/choice-sel.png':'../../images/choice-nor.png'"
            mode="aspectFit"
          >
          <span class="get-way">快递</span>
        </div>
        <div @click="choiceWay(1)">
          <img
            class="choice-icon"
            :src="getWay===1?'../../images/choice-sel.png':'../../images/choice-nor.png'"
            mode="aspectFit"
          >
          <span class="get-way">自提</span>
        </div>
      </div>
      <div style="height:15rpx"></div>
      <div class="row between">
        <div style="font-size: 28rpx;">快递地址</div>
        <img
          :animation="animatRotate"
          @click="showAddress"
          class="arrow"
          src="../../images/arrow_bottom.png"
          mode="aspectFit"
        >
      </div>
      <div style="height:15rpx"></div>

      <div
        :style="'height:'+addressHeight+'rpx'"
        class="address"
        :animation="animatheight"
      >
        <div
          @click="changeAddress"
          class="row"
          v-if="getWay==0"
        >
          <div
            class="address-detail"
            v-if="orderInfo.address"
          >
            <div class="row">
              <div class="detail-name">收货地址</div>
              <div class="detail-content">：{{
                orderInfo.address.province+
                orderInfo.address.city+
                orderInfo.address.country+
                orderInfo.address.address
                }}</div>
            </div>
            <div class="row">
              <div class="detail-name">联系人</div>
              <div class="detail-content">：{{orderInfo.address.receiver_name}}</div>
            </div>
            <div class="row">
              <div class="detail-name">电话</div>
              <div class="detail-content">：{{orderInfo.address.phone}}</div>
            </div>
          </div>
        </div>
        <div v-if="getWay==1">
          <div
            @click="changeAddress(index)"
            class="row"
            v-for="(item,index) in shopAddress"
            :key=index
          >
            <img
              class="choice-icon-sm"
              :src="takeAddress==index?'../../images/choice-sel-2.png':'../../images/choice-nor.png'"
              mode="aspectFit"
            >
            <div class="address-detail">
              <div style="height:10rpx"></div>
              <div class="row">
                <div class="detail-name"> 收货地址</div>
                <div>：{{item.province+item.city+item.country+item.address}}</div>
              </div>
              <div class="row">
                <div class="detail-name">联系人</div>
                <div>：{{item.receiver_name}}</div>
              </div>
              <div class="row">
                <div class="detail-name">电话</div>
                <div>：{{item.phone}}</div>
              </div>
              <div style="height:10rpx"></div>
            </div>
          </div>
        </div>

      </div>

      <div class="split"></div>
      <div class="row">
        <div class="item-name">买家留言</div>
        <input
          class="leaveMsg"
          type="text"
          v-model="leaveMsg"
        >
      </div>
      <div class="split"></div>
      <div class="row between ">
        <div class="item-name">发票信息</div>
        <a
          href="/pages/invoice/main"
          class="row"
          hover-class="none"
        >
          <div class="invoice">{{invoiceData.name}}</div>
          <img
            class="arrow"
            src="../../images/arrow_right.png"
            mode="aspectFit"
          >
        </a>
      </div>
      <div class="split"></div>
      <div
        class="row between start-item"
        v-if="orderInfo.total_info"
        style="margin-bottom:40rpx;"
      >
        <div>
          <div class="item-name">商品总额</div>
          <div>运费: ￥0</div>
        </div>
        <div class="col">
          <div>现价 ￥{{orderInfo.total_info.payment}}</div>
          <div v-if='discount&&discount.success'>-优惠券 {{discount.data.title}}</div>
          <div class="price">实付 ￥{{realPrice}}</div>
        </div>
      </div>
    </div>

    <div :style="isIpx?'height: 158rpx':'height: 90rpx'"></div>
    <div class="fixed-bottom">
      <img
        src="../../images/pay-btn.png"
        mode="aspectFit"
        class="pay-btn"
        @click="toPay"
      >
      <div
        v-if="isIpx"
        class="for-iphonex"
      ></div>
    </div>
  </div>
</template>

<script>
import NormalTitle from '@/components/NormalTitle'
import { request } from '@/utils'
export default {
  components: {
    NormalTitle
  },
  data () {
    return {
      isIpx: false,
      orderInfo: {},
      shopAddress: [],
      isShow: true,
      getWay: undefined, // 0:快递, 1:自提
      takeAddress: 0,
      animatRotate: {},
      discountCode: '',
      discount: null,
      discountPrice: 0,
      realPrice: 0,
      leaveMsg: '',
      invoiceData: { name: '普通个人不开发票' },
      payying: false
    }
  },
  computed: {
    addressHeight () {
      if (!this.isShow || this.getWay === undefined) {
        return 0
      } else {
        if (this.getWay === 0 && this.checkAddr(this.orderInfo.address)) {
          return 105
        } else if (this.getWay === 1 && this.shopAddress.length > 0) {
          return 106 * this.shopAddress.length
        } else {
          return 0
        }
      }
    }
  },
  methods: {
    async getAccountInfo () {
      let data = this.$root.$mp.query
      var res
      if (data) {
        res = await request('/v1/order/prepare-orders', 'post', data)
        this.orderInfo = res.data
        if (!this.checkAddr(this.orderInfo.address)) {
          this.orderInfo.address = {}
        }

        this.realPrice = this.orderInfo.total_info.payment
      }
      res = await request('/v1/order/get-shop-address', 'get')
      this.shopAddress = res.data.items
    },
    async checkCode (e) {
      if (e.mp.detail.value.length > 9) {
        var res = await request(
          '/v1/coupon/search-coupon?code=' + this.discountCode,
          'get'
        )
        this.discount = res.data
        if (res.data.success) {
          var result = await request('/v1/order/get-shop-address', 'get', {
            admin_user_id: this.discount.data.admin_user_id
          })
          this.shopAddress = result.data.items
          this.realPrice =
            Math.round(
              this.orderInfo.total_info.payment.replace(',','') * this.discount.data.price * 100
            ) / 100
        } else {
          this.realPrice = this.orderInfo.total_info.payment
        }
      } else {
        this.discount = null
      }
    },
    async toPay () {
      if (this.getWay === undefined) {
        wx.showToast({
          title: '请先选择配送方式',
          icon: 'none'
        })
        return
      }
      var address
      if (this.getWay === 0) {
        if (this.checkAddr(this.orderInfo.address)) {
          address = JSON.parse(JSON.stringify(this.orderInfo.address))
        } else {
          wx.showToast({
            title: '请先填写快递地址',
            icon: 'none'
          })
          return
        }
      } else if (this.getWay === 1) {
        address = JSON.parse(
          JSON.stringify(this.shopAddress[this.takeAddress])
        )
      }
      if (!this.payying) {
        this.payying = true
        let queryData = this.$root.$mp.query
        var data = Object.assign(address, queryData)
        data.buyer_message = this.leaveMsg
        data.express_type = this.getWay
        if (this.invoiceData.id) {
          data.receipt_id = this.invoiceData.id
        }
        if (this.discount !== null && this.discount.success) {
          data.user_coupon_ids = this.discount.data.id
        }
        console.log(data)
        var res = await request('/v1/order', 'post', data)
        var _this = this
        if (res.data.success) {
          this.globalData.cartRefresh = true
          var orderId = res.data.status
          var result = await request('/v1/pay', 'post', {
            orderId
          })
          wx.requestPayment({
            timeStamp: result.data.timestamp,
            nonceStr: result.data.nonceStr,
            package: result.data.package,
            signType: 'MD5',
            paySign: result.data.paySign,
            complete (res) {
              _this.payying = false
              wx.redirectTo({
                url: '/pages/orderDetail/main?order_id=' + orderId
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        }
      }
    },
    arrowRotate (angle) {
      var animatRotate = wx.createAnimation({
        duration: 200,
        timingFunction: 'ease-in',
        transformOrigin: '50% 50% 0'
      })
      animatRotate.rotate(angle).step()
      this.animatRotate = animatRotate.export()
    },
    checkAddr (obj) {
      if (obj === null) {
        return false
      }
      var empty = true
      for (var key in obj) {
        empty = false
        if (obj.hasOwnProperty(key)) {
          if (obj[key] === '') {
            return false
          }
        }
      }
      if (empty) {
        return false
      } else {
        return true
      }
    },
    wxChooseAddress () {
      var _this = this
      wx.chooseAddress({
        success (res) {
          _this.$set(_this.orderInfo.address, 'receiver_name', res.userName)
          _this.$set(_this.orderInfo.address, 'province', res.provinceName)
          _this.$set(_this.orderInfo.address, 'phone', res.telNumber)
          _this.$set(_this.orderInfo.address, 'city', res.cityName)
          _this.$set(_this.orderInfo.address, 'country', res.countyName)
          _this.$set(_this.orderInfo.address, 'address', res.detailInfo)
        },
        fail () {
          wx.getSetting({
            success (res) {
              if (!res.authSetting['scope.address']) {
                wx.openSetting()
              }
            }
          })
        }
      })
    },
    choiceWay (way) {
      this.getWay = way
      if (way === 0 && !this.checkAddr(this.orderInfo.address)) {
        this.wxChooseAddress()
      }
      this.isShow = true
      this.arrowRotate(180)
    },
    changeAddress (index) {
      if (this.getWay === 0) {
        this.wxChooseAddress()
      } else if (this.getWay === 1) {
        this.takeAddress = index
      }
    },
    showAddress () {
      if (this.getWay === undefined) {
        wx.showToast({
          title: '请先选择配送方式',
          icon: 'none'
        })
        return
      }
      var angle = this.isShow ? 0 : 180
      this.arrowRotate(angle)
      this.isShow = !this.isShow
    }
  },
  created () {
    this.isIpx = this.globalData.isIpx
  },
  onLoad () {
    this.getWay = undefined
  },
  mounted () {
    this.leaveMsg = ''
    this.discountCode = ''
    this.discount = null
    this.getAccountInfo()
    this.arrowRotate(180)
  },
  onShow () {
    var pages = getCurrentPages()
    var currPage = pages[pages.length - 1]
    if (currPage.receipt) {
      this.invoiceData = currPage.receipt
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  font-size: 26rpx;
  .card {
    margin: 0 25rpx;
    display: flex;
    align-items: center;
    height: 200rpx;
    background: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    .thumb {
      width: 160rpx;
      height: 160rpx;
      border-radius: 15rpx;
      margin-right: 25rpx;
    }
    .info {
      width: 455rpx;
      height: 160rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      // border: 1rpx solid #000;
      .spec {
        font-size: 20rpx;
        color: #747474;
        margin-bottom: 5rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        position: relative;
        bottom: 10rpx;
      }
      .text {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        height: 75rpx;
        font-size: 600;
      }
      .row {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        height: 35rpx;
        line-height: 26rpx;

        .price {
          color: #b93a39;
          font-size: 36rpx;
          font-weight: 400;
          .price-icon {
            font-size: 24rpx;
            display: inline-block;
          }
        }
        .count {
          font-size: 20rpx;
        }
      }
    }
  }
  .session {
    margin: 25rpx 25rpx 0;
    .tips {
      font-size: 24rpx;
      margin-left: 20rpx;
      // height: 60rpx;
      width: 200rpx;
      line-height: 25rpx;
      overflow: hidden;
    }
    .split {
      height: 20rpx;
      margin-bottom: 20rpx;
      border-bottom: 1rpx solid #f0f0f0;
      background: transparent;
    }
    .address {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      font-size: 20rpx;
      background: #f6f6f6;
      overflow: hidden;
      border-radius: 0 0 15rpx 15rpx;
      height: 0rpx;
      transition: All 0.3s ease-in;
      .address-detail {
        margin: 0 30rpx;
        .detail-name {
          width: 100rpx;
          height: 26rpx;
          text-align: justify;
        }
        .detail-name:after {
          content: "";
          padding-left: 100%;
          display: inline-block;
        }
        .detail-content {
          width: 550rpx;
          height: 26rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .row {
    color: #6d6d6d;
    .item-name {
      font-size: 32rpx;
      font-weight: 500;
      color: #000;
    }
    .discount {
      width: 300rpx;
      border: 1rpx solid #e2e2e2;
      color: #cdb27e;
      padding: 5rpx 10rpx;
      font-weight: 600;
      margin-left: 40rpx;
    }
    .leaveMsg {
      width: 300rpx;
      border: 1rpx solid #e2e2e2;
      color: #6d6d6d;
      padding: 5rpx 10rpx;
      font-weight: 600;
      margin-left: 40rpx;
    }
    .fake {
      width: 180rpx;
    }
    .choice-icon {
      width: 35rpx;
      height: 35rpx;
      padding: 0 20rpx 0 60rpx;
      vertical-align: middle;
    }
    .choice-icon-sm {
      width: 30rpx;
      height: 30rpx;
      padding: 20rpx 0 20rpx 20rpx;
    }
    .arrow {
      width: 35rpx;
      height: 35rpx;
    }

    .invoice {
      width: 120rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .col {
      text-align: right;
      .price {
        color: #b93a39;
        font-weight: 600;
      }
    }
  }
  .pay-btn {
    width: 750rpx;
    height: 89rpx;
  }
}
</style>
